package kr.moiba.tester.web;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.moiba.board.domain.Board;
import kr.moiba.board.service.BoardSvc;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 이 영호(Youngho Lee)
 */

@Controller
@RequestMapping("/tester")
public class TesterCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	private BoardSvc boardSvc;
		
	@RequestMapping(value={"/notice.do"})
	public Map<String, Object> noticeList(HttpServletRequest request) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("type", 4);
		
		String searchType = ServletRequestUtils.getStringParameter(request, "searchType", "");
		String searchWord = ServletRequestUtils.getStringParameter(request, "searchWord", "");
		
		if(searchType.equals("title")){
			condition.put("title", searchWord);	
		}else if(searchType.equals("cont")){
			condition.put("cont", searchWord);
		}else if(searchType.equals("name")){
			condition.put("userNm", searchWord);
		}
		
		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.putAll(boardSvc.findbyListPaging(condition));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}
	
	@RequestMapping(value={"/noticeDetail.do"})
	public Map<String, Object> noticeDetail(HttpSession session, @RequestParam(required=true, value="idx") Integer idx) throws Exception {
		
		String userId = (String)session.getAttribute("userId");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("idx", idx);
		condition.put("userId", userId);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Board board = boardSvc.findby(condition);
		if(board != null){
			resultMap.put("board", board);
		}else{
			throw new Exception("[ERROR] 등록되지 않은 글 입니다.");
		}

		return resultMap;
	}

	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request, HttpSession session, @RequestParam(required=false, value="idx") Integer idx) throws Exception {
		String userId = (String)session.getAttribute("userId");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("idx", idx);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("board", boardSvc.findby(condition));
		
		//테스트 결과 목록
		condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("type", 5);
		
		String searchType = ServletRequestUtils.getStringParameter(request, "searchType", "");
		String searchWord = ServletRequestUtils.getStringParameter(request, "searchWord", "");
		
		if(searchType.equals("title")){
			condition.put("title", searchWord);	
		}else if(searchType.equals("cont")){
			condition.put("cont", searchWord);
		}else if(searchType.equals("name")){
			condition.put("userNm", searchWord);
		}

		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);

		resultMap.putAll(boardSvc.findbyListPaging(condition));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}

	@RequestMapping(value={"/detail.do"})
	public Map<String, Object> detail(HttpSession session, @RequestParam(required=true, value="idx") Integer idx) throws Exception {
		
		String userId = (String)session.getAttribute("userId");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("idx", idx);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Board board = boardSvc.findby(condition);
		if(board != null){
			resultMap.put("board", board);
		}else{
			throw new Exception("[ERROR] 등록되지 않은 글 입니다.");
		}

		return resultMap;
	}

	@RequestMapping(value={"/submit.do"})
	public String submit(HttpServletRequest request, HttpSession session, Board board) throws Exception {

		//첨부파일 업로드
		MultipartFile boardfile = board.getBoardFile();
		if(boardfile != null && ! boardfile.isEmpty()){
			long time = Calendar.getInstance().getTimeInMillis();
			String prefixNm = "tester_" + Long.toString(time);
			String fileNm = prefixNm +"."+(boardfile.getOriginalFilename()).split("\\.")[1];

			//업로드 경로
			String uploadDir = messages.getMessage("file.boardfile.uploadDir");
			
			//viewUrl
			String viewUrl = messages.getMessage("file.boardfile.viewUrl");

			File file = new File(uploadDir+fileNm);
			String url = viewUrl+fileNm;
			board.setFile(url);
			
			if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
				new File(uploadDir).mkdirs();
			}
			boardfile.transferTo(file);
		}
		
		String userId = (String)session.getAttribute("userId");
		String userIp = request.getRemoteAddr();
		//기본 정보 지정
		board.setCreatedId(userId);
		board.setCreatedIp(userIp);
		board.setType(5);
		
		if(board.getIdx() != null){//update
			board.setModifiedId(userId);
			board.setModifiedIp(userIp);
			
			String fAct = ServletRequestUtils.getStringParameter(request, "fAct", "modify");
			if(fAct.equals("remove")){//삭제
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("type", 5);
				Integer[] idx = {board.getIdx()};
				condition.put("idx", idx);
				boardSvc.remove(condition);
			}else{//수정
				boardSvc.modify(board);
			}
		}else{//등록
			boardSvc.add(board);
		}
		
		return "tester/result";
	}
	
	@RequestMapping(value={"/qna.do"})
	public Map<String, Object> formQna(HttpServletRequest request, HttpSession session, @RequestParam(required=false, value="idx") Integer idx) throws Exception {
		String userId = (String)session.getAttribute("userId");
	
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		//문의하기(체험단) 목록
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("type", 6);
		
		String searchType = ServletRequestUtils.getStringParameter(request, "searchType", "");
		String searchWord = ServletRequestUtils.getStringParameter(request, "searchWord", "");
		
		if(searchType.equals("title")){
			condition.put("title", searchWord);	
		}else if(searchType.equals("cont")){
			condition.put("cont", searchWord);
		}else if(searchType.equals("name")){
			condition.put("userNm", searchWord);
		}

		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);

		resultMap.putAll(boardSvc.findbyListPaging(condition));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}
	
	@RequestMapping(value={"/formQna.do"})
	public Map<String, Object> form(HttpSession session, @RequestParam(required=false, value="idx") Integer idx) throws Exception {
		String userId = (String)session.getAttribute("userId");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("idx", idx);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("board", boardSvc.findby(condition));
		
		return resultMap;
	}

	@RequestMapping(value={"/detailQna.do"})
	public Map<String, Object> detailQna(HttpSession session, @RequestParam(required=true, value="idx") Integer idx) throws Exception {
		
		String userId = (String)session.getAttribute("userId");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("userId", userId);
		condition.put("idx", idx);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Board board = boardSvc.findby(condition);
		if(board != null){
			resultMap.put("board", board);
		}else{
			throw new Exception("[ERROR] 등록되지 않은 글 입니다.");
		}

		return resultMap;
	}

	@RequestMapping(value={"/submitQna.do"})
	public String submitQna(HttpServletRequest request, HttpSession session, Board board) throws Exception {
		
		String userId = (String)session.getAttribute("userId");
		String userIp = request.getRemoteAddr();
		//기본 정보 지정
		board.setCreatedId(userId);
		board.setCreatedIp(userIp);
		board.setType(6);
		
		if(board.getIdx() != null){//update
			String fAct = ServletRequestUtils.getStringParameter(request, "fAct", "modify");
			if(fAct.equals("remove")){//삭제
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("modifiedId", userId);
				condition.put("modifiedIp", userIp);
				condition.put("type", 6);
				Integer[] idx = {board.getIdx()};
				condition.put("idx", idx);
				boardSvc.remove(condition);
			}else{//수정
				board.setModifiedId(userId);
				board.setModifiedIp(userIp);
				boardSvc.modify(board);
			}
		}else{//등록
			boardSvc.add(board);
		}
		
		return "tester/resultQna";
	}

}